package cn.xdf.demo01;

import cn.xdf.dao.GoodsDao;
import cn.xdf.entity.Goods;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Demo01_创建索引 {

    @Test
    public void test01() throws IOException {

        GoodsDao goodsDao = new GoodsDao();

        //拿到原始数据
        List<Goods> goodsList = goodsDao.findAll();

        //储存所有文档
        List<Document> docList=new ArrayList<>();
        for(Goods goods:goodsList){
            //一个goods对象对应一个文档对象
            Document doc=new Document();
            //添加域对象
            doc.add(new StringField("id",goods.getId()+"", Field.Store.YES));
            doc.add(new TextField("name",goods.getName(), Field.Store.YES));
            doc.add(new TextField("title",goods.getTitle(), Field.Store.YES));
            doc.add(new DoubleField("price",goods.getPrice(), Field.Store.YES));
            doc.add(new StoredField("pic",goods.getPic()));//一定会存，所以没后面参数,存到索引库

            docList.add(doc);
        }

        //创建ik分析器-分词器
        IKAnalyzer analyzer=new IKAnalyzer();

        //索引库配置对象
        IndexWriterConfig config=new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);

        /**
         *  设置索引库打开方式
         *  APPEND:每次执行都会将本次产生的数据追加到索引库
         *  CREATE:每次运行前会清空索引库，每次执行都会将本次产生的数据追加到索引库,每次运行前都会清空
         *  CREATE_OR_APPEND:如果有索引库就追加，如果没有就创建
         */

        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

        //创建索引库目录对象，指定索引库目录,存在磁盘
        FSDirectory dir = FSDirectory.open(new File("D:/aaa/index"));

        //创建索引库操作对象
        IndexWriter indexWriter=new IndexWriter(dir,config);

        //添加索引
        indexWriter.addDocuments(docList);

        //提交事务
        indexWriter.commit();


        indexWriter.commit();
        dir.close();



    }
}
